package io.github.zhx666666.word;

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.List;

public class MergeWordDocuments {
    public static void main(String[] args) {
        try {
            // 打开目标文档
            FileInputStream targetFileStream = new FileInputStream("H:\\aa.docx");
            XWPFDocument targetDocument = new XWPFDocument(targetFileStream);
            targetFileStream.close();

            // 打开要合并的文档
            FileInputStream sourceFileStream = new FileInputStream("H:\\bb.docx");
            XWPFDocument sourceDocument = new XWPFDocument(sourceFileStream);
            sourceFileStream.close();

            // 找到目标文档中的标题，例如：第二章标题
            String targetTitle = "aaaaaaaa";

            // 创建一个新的 XWPFDocument 对象来表示要合并的文档
            XWPFDocument mergedDocument = new XWPFDocument();

            // 复制目标文档的内容，直到找到目标标题
            boolean foundTargetTitle = false;
            for (XWPFParagraph paragraph : targetDocument.getParagraphs()) {
                if (!foundTargetTitle) {
                    if (paragraph.getText().contains(targetTitle)) {
                        foundTargetTitle = true;
                    }
                    XWPFParagraph newParagraph = mergedDocument.createParagraph();
                    newParagraph.createRun().setText(paragraph.getText());
                }
            }

            // 复制要合并的文档的内容
//            for (XWPFParagraph paragraph : sourceDocument.getParagraphs()) {
//                XWPFParagraph newParagraph = mergedDocument.createParagraph();
//                newParagraph.createRun().setText(paragraph.getText());
//            }


            // 复制段落和样式
            for (XWPFParagraph paragraph : sourceDocument.getParagraphs()) {
                XWPFParagraph newParagraph = targetDocument.createParagraph();
                newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
                for (XWPFRun run : paragraph.getRuns()) {
                    XWPFRun newRun = newParagraph.createRun();
                    newRun.getCTR().setRPr(run.getCTR().getRPr());
                    newRun.setText(run.text());
                }
            }

            // 保存合并后的文档
            FileOutputStream mergedFileStream = new FileOutputStream("H:\\cc1122.docx");
            mergedDocument.write(mergedFileStream);
            mergedFileStream.close();

            System.out.println("文档合并完成。");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

